from io import BytesIO
import fetch
import store

from tkinter import *
from tkinter import ttk, font as tk_font

import requests
from PIL import Image,ImageTk

import copy

# 动画字典字段名
ANIME_KEYS = [
    "#index",  # 序号
    "cn_title",
    "jp_title",
    "type",
    "tags",
    "staff",
    "cast",
    "link",
    "broadcast",
    "episodes",
    "cover",
]
ANIME_CN_TITLE = "cn_title"
ANIME_JP_TITLE = "jp_title"
ANIME_TYPE = "type"
ANIME_TAGS = "tags"
ANIME_STAFF = "staff"
ANIME_CAST = "cast"
ANIME_LINK = "link"
ANIME_BROADCAST = "broadcast"
ANIME_EPISODE = "episodes"
ANIME_COVER = "cover"


cache_animes = []
temp_animes = []


fetch.init()

root = Tk()
root.title("查看动画")
root.geometry("640x480")

# 字体
font_name = ""
if tk_font.families().count("微软雅黑"):
    font_name = "微软雅黑"
elif tk_font.families().count("song ti"):
    font_name = "song ti"

tk_font.nametofont("TkDefaultFont").configure(family=font_name, size=14)
font_title = (font_name, 20)
font = (font_name, 18)
font_18 = (font_name, 18)
font_16 = (font_name, 16)
font_14 = (font_name, 14)
font_12 = (font_name, 12)
font_10 = (font_name, 10)
root.option_add("*Font", (font_name, 12))
# 创建Frame

frame = Frame(root, padx=20, pady=10)
frame.pack(fill="both", expand=False)

table_frame = Frame(root, padx=10, pady=20)
table_frame.pack(fill="both", expand=True)

# cover
def create_cover_photo(url: str,width: int=60):
    img=Image.open(BytesIO(requests.get(url).content))
    w,h=img.size
    aspect_ratio=w/h
    img=img.resize((width,int(width/aspect_ratio)))
    photo=ImageTk.PhotoImage(img)
    return photo
#view windows
def create_view_window(anime: dict):
    def create_frame():
        return Frame(view_window)
    global cover

    view_window=Toplevel(root)
    # view_window.geometry("640x480")
    view_window.title("view")

    cover=create_cover_photo(anime[ANIME_COVER],400)
    label_cover=Label(view_window,image=cover)
    label_cover.pack()

    del anime[ANIME_COVER]
    for key,value in anime.items():
        frame=create_frame();
        Label(frame,text=key).grid(row=0,column=0,sticky='e')
        if type(value)==list:
            for i,v in enumerate(value):
                Label(frame,text=v).grid(row=i,column=1,sticky='w')
        else:
            Label(frame,text=value).grid(row=0,column=1,sticky='w')
        frame.pack(fill='both')

    close_button = Button(view_window, text="关闭窗口", command=view_window.destroy)
    close_button.pack()

# 创建Label
label = Label(frame, text="选择季度", width=8, font=font_16)
label.grid(row=0, column=0, pady=10, sticky="nsew")

# 选择季度
combo_season = ttk.Combobox(frame, values=fetch.get_seasons(), width=8, font=font_14)
combo_season.grid(row=0, column=1, pady=10, sticky="ew")
combo_season.current(0)

KEY_COMBOBOX_SELECTED = "<<ComboboxSelected>>"


def show_selection(event):
    selected_season = combo_season.get()
    print(selected_season)


combo_season.bind(KEY_COMBOBOX_SELECTED, show_selection)
# 动画筛选项


# update combobox values
def update_combo_values(combobox, values):
    combobox["values"] = values


# 生成combo选项
def gen_combo_options(options: list = []) -> list:
    return ["不筛选"] + options


# 已选择
def is_optioned(option: str):
    return not option == gen_combo_options()[0]


# util: 筛选animes,按子列表中元素匹配(至少一个则为True)
def get_filter_sublist(animes: list, anime_key: str, filter_value) -> list:
    return list(filter(lambda x: any(filter_value in s for s in x[anime_key]), animes))


# 生成set集合list
def get_set_list(animes: list, anime_key) -> list:
    types = list(map(lambda x: x[anime_key], animes))
    return list(set(x for sublist in types for x in sublist))


def update_combos(animes: list):
    update_combo_values(
        combo_anime_type, gen_combo_options(get_set_list(animes, ANIME_TYPE))
    )
    update_combo_values(
        combo_anime_tags, gen_combo_options(get_set_list(animes, ANIME_TAGS))
    )


def filter_combos_event(event):
    broadcast = combo_broadcast.get()
    anime_type = combo_anime_type.get()
    anime_tag = combo_anime_tags.get()
    anime_title = entry_title.get()
    print("fitler_combos_event:", broadcast, anime_type, anime_tag, anime_title)

    global cache_animes
    animes = cache_animes
    if is_optioned(broadcast):
        animes = get_filter_sublist(animes, ANIME_BROADCAST, broadcast)
    if is_optioned(anime_type):
        animes = get_filter_sublist(animes, ANIME_TYPE, anime_type)
    if is_optioned(anime_tag):
        animes = get_filter_sublist(animes, ANIME_TAGS, anime_tag)
    if anime_title and len(anime_title) > 0:
        animes = list(
            filter(
                lambda x: anime_title in x[ANIME_CN_TITLE]
                or anime_title in x[ANIME_JP_TITLE],
                animes,
            )
        )
    table_refresh_animes(animes)


# label
label_filter = Label(frame, text="筛选项", width=8, font=font_16)
label_filter.grid(row=2, column=0, pady=10, sticky="nsew")
## 按名搜索框
Label(frame, text="名称", width=4, font=font_12).grid(row=3, column=0, sticky="e")
entry_title = Entry(frame, font=font_12, highlightcolor="yellow")
entry_title.grid(row=3, column=1, columnspan=2, sticky="ew")
entry_title.bind("<KeyRelease>", filter_combos_event)
## 按播出时间
Label(frame, text="播出时间:", width=8, font=font_12).grid(row=4, column=0, sticky="e")
broadcast_values = gen_combo_options(
    ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
)
combo_broadcast = ttk.Combobox(
    frame, values=broadcast_values, state="readonly", width=6, font=font_12
)
combo_broadcast.grid(row=4, column=1, pady=10, sticky="w")
combo_broadcast.current(0)
combo_broadcast.bind(KEY_COMBOBOX_SELECTED, filter_combos_event)

## 按类型
Label(frame, text="类型", width=4, font=font_12).grid(row=5, column=0, sticky="e")
combo_anime_type = ttk.Combobox(
    frame, values=gen_combo_options(), state="readonly", width=12, font=font_12
)
combo_anime_type.current(0)
combo_anime_type.grid(row=5, column=1, pady=0, sticky="w")
combo_anime_type.bind(KEY_COMBOBOX_SELECTED, filter_combos_event)
## 按tag
Label(frame, text="标签", width=4, font=font_12).grid(row=6, column=0, sticky="e")
combo_anime_tags = ttk.Combobox(
    frame,
    values=gen_combo_options(),
    state="readonly",
)
combo_anime_tags.grid(row=6, column=1, sticky="w")
combo_anime_tags.current(0)
combo_anime_tags.bind(KEY_COMBOBOX_SELECTED, filter_combos_event)

font_button = font_14
# label
label_main = Label(frame, text="主要功能", width=8, font=font_16)
label_main.grid(row=1, column=0, pady=10, sticky="nsew")


# csv按钮
def gen_csv():
    store.write_csv(combo_season.get())


submit_button = Button(
    frame, text="生成csv文件", font=font_button, width=12, command=gen_csv
)
submit_button.grid(row=1, column=1, pady=10, sticky="nsew")


# 查看按钮
# 向table中插入anime list
def table_insert_animes(animes: list):
    for index, anime in enumerate(animes):
        data = []
        data.append(index)
        for key in ANIME_KEYS[1:]:
            data.append(anime[key])
        table.insert("", END, text=index, values=data)


def table_clear():
    table.delete(*table.get_children())


def table_refresh_animes(animes: list):
    temp_animes = animes
    table_clear()
    table_insert_animes(temp_animes)


# view submit
def view_season():
    # insert animes
    global cache_animes, temp_animes

    cache_animes = fetch.load_animes(combo_season.get())
    temp_animes = cache_animes
    table_refresh_animes(temp_animes)
    update_combos(temp_animes)


view_button = Button(
    frame, text="查看季度动画", font=font_button, width=12, command=view_season
)
view_button.grid(row=1, column=2, pady=10, sticky="w")

# 动画表格
# table_selected
def table_row_selected(event):
    global temp_animes
    try:
        index=table.item(table.focus())['values'][0]
        anime=copy.deepcopy(temp_animes[index])
        anime[ANIME_LINK]=list(map(lambda x:f'{x['name']}({x['url']})',anime[ANIME_LINK]))
        create_view_window(anime)
    except:
        print("table选中value为空")
        
xscroll = Scrollbar(table_frame, orient=HORIZONTAL)
yscroll = Scrollbar(table_frame, orient=VERTICAL)

table = ttk.Treeview(
    table_frame,
    height=10,
    columns=ANIME_KEYS,
    show="headings",
    xscrollcommand=xscroll.set,
    yscrollcommand=yscroll.set,
)

# 样式
table_style = ttk.Style()

for key in ANIME_KEYS:
    table.heading(key, text=key)
    table.column(key, width=100, minwidth=10)
table.column("#index", width=30, stretch=False)

xscroll.config(command=table.xview)
xscroll.pack(side=BOTTOM, fill=X)
yscroll.config(command=table.yview)
yscroll.pack(side=RIGHT, fill=Y)

table.bind("<<TreeviewSelect>>",table_row_selected)

table.pack(fill=BOTH, expand=True)

root.mainloop()
